// dh-patients 云对象 - 患者档案管理
const db = uniCloud.database();
const _ = db.command;
const { autoMountHospitalId, softDelete, batchSoftDelete, getUserById, getUserList } = require('dh-common');

/**
 * 统一响应格式化辅助函数
 */
function formatResponse(code, data = null, message = 'success', extraFields = {}) {
	return {
		code,
		data,
		message,
		success: (code === 200 || code === 201),
		timestamp: Date.now(),
		...extraFields
	};
}

/**
 * 统一错误响应辅助函数
 */
function formatError(error, defaultMessage = '操作失败') {
	console.error('[dh-patients] 错误:', error);
	return {
		code: 500,
		message: error.message || defaultMessage,
		success: false,
		timestamp: Date.now()
	};
}

/**
 * 解析JWT Token获取payload
 */
function parseToken(token) {
	if (!token || typeof token !== 'string') return null;
	try {
		const parts = token.split('.');
		if (parts.length !== 3) return null;
		const payload = Buffer.from(parts[1], 'base64').toString('utf-8');
		return JSON.parse(payload);
	} catch (error) {
		console.error('[dh-patients] 解析token失败:', error);
		return null;
	}
}

/**
 * 获取性别文本
 */
function getGenderText(gender) {
	const genderMap = {
		0: '未知',
		1: '男',
		2: '女'
	};
	return genderMap[gender] || '未知';
}

module.exports = {

	/**
	 * 请求前拦截
	 */
	async _before(methodName, params) {
		const clientInfo = this.getClientInfo();
		const tokenString = clientInfo?.uniIdToken;
		const tokenPayload = parseToken(tokenString);

		const writeMethods = ['create', 'update', 'delete'];
		if (methodName && writeMethods.some(method => methodName.toLowerCase().includes(method))) {
			if (!tokenPayload?.uid) {
				throw new Error('401|未授权的访问');
			}
		}

		if (params && typeof params === 'object') {
			for (let key in params) {
				if (typeof params[key] === 'string') {
					params[key] = params[key].trim();
				}
			}
		}
	},

	/**
	 * 获取患者档案详情
	 */
	async getPatientById(id) {
		try {
			if (!id) {
				return formatResponse(400, null, '患者ID不能为空');
			}

			const res = await db.collection('dh-patients').doc(id).get();
			if (res.data.length === 0) {
				return formatResponse(404, null, '患者档案不存在');
			}

			const patientData = res.data[0];

			// 使用统一的用户查询工具获取用户信息（自动解密）
			// 患者查询需要 allowPatients=true
			if (patientData.user_id) {
				const userInfo = await getUserById(patientData.user_id, 'full', true, true);
				
				if (userInfo) {
					patientData.patient_name = userInfo.realName || userInfo.displayName || '';
					patientData.username = userInfo.username || '';
					patientData.mobile = userInfo.mobile || '';
					patientData.mobile_confirmed = userInfo.mobile_confirmed;
					patientData.email = userInfo.email || '';
					patientData.email_confirmed = userInfo.email_confirmed;
					patientData.avatar = userInfo.avatar || '';
					patientData.user_info = userInfo;
				}
			}

			// 添加性别文本
			patientData.gender_text = getGenderText(patientData.gender);

			return formatResponse(200, patientData);
		} catch (error) {
			return formatError(error, '获取患者档案失败');
		}
	},

	/**
	 * 获取患者档案列表
	 */
	async listPatients(query = {}, skip = 0, limit = 20) {
		try {
			if (typeof query !== 'object' || query === null || Array.isArray(query)) {
				query = {};
			}
		skip = parseInt(skip) || 0;
		limit = parseInt(limit) || 20;

		// 默认不显示已删除记录
		query.is_deleted = false;

		// 查询总数
		const countRes = await db.collection('dh-patients')
			.where(query)
			.count();

			const totalCount = countRes.total || 0;

			// 查询患者列表
			const patientsRes = await db.collection('dh-patients')
				.where(query)
				.skip(skip)
				.limit(limit)
				.orderBy('create_time', 'desc')
				.get();

			// 获取所有关联的 user_id
			const userIds = patientsRes.data
				.filter(patient => patient.user_id)
				.map(patient => patient.user_id);

			// 批量查询用户信息（使用统一的用户查询工具）
			let usersMap = {};
			if (userIds.length > 0) {
				// 使用 getUserList 查询所有患者用户，然后过滤出需要的
				const allPatients = await getUserList({
					includeRoles: ['patient'],
					allowPatients: true,
					format: 'full',
					limit: 1000,
					decryptSensitiveInfo: true
				});
				
				// 构建用户ID到用户信息的映射
				allPatients.forEach(user => {
					if (userIds.includes(user._id)) {
						usersMap[user._id] = user;
					}
				});
			}

		// 合并患者信息和用户信息
		const patientsList = patientsRes.data.map(patient => {
			const userData = usersMap[patient.user_id];
			return {
				_id: patient._id,
				user_id: patient.user_id || '',
				patient_name: userData?.realName || userData?.displayName || patient.patient_name || '',
				gender: patient.gender,
				gender_text: getGenderText(patient.gender),
				birth_date: patient.birth_date || null,
				blood_type: patient.blood_type || '未知',
				allergies: patient.allergies || [],
				chronic_diseases: patient.chronic_diseases || [],
				emergency_contact: patient.emergency_contact || '',
				emergency_phone: patient.emergency_phone || '',
				hospital_id: patient.hospital_id,
				create_time: patient.create_time || null,
				// 关联的用户信息
				username: userData?.username || '',
				mobile: userData?.mobile || '',
				mobile_confirmed: userData?.mobile_confirmed,
				user_info: userData
			};
		});

			return formatResponse(200, patientsList, 'success', { count: totalCount });
		} catch (error) {
			return formatError(error, '获取患者列表失败');
		}
	},

	/**
	 * 创建患者档案
	 */
	async createPatient(data) {
		try {
			if (!data.user_id) {
				return formatResponse(400, null, '用户ID不能为空');
			}

			let patientData = {
				user_id: data.user_id,
				gender: data.gender || 0,
				birth_date: data.birth_date || null,
				id_card: data.id_card || '',
				blood_type: data.blood_type || '未知',
				allergies: data.allergies || [],
				chronic_diseases: data.chronic_diseases || [],
				emergency_contact: data.emergency_contact || '',
				emergency_phone: data.emergency_phone || '',
				is_deleted: false,  // 软删除字段，默认未删除
				create_time: Date.now(),
				update_time: Date.now()
			};

			// 🏥 自动挂载医院ID（单一医院系统特性）
			patientData = await autoMountHospitalId(patientData);

			// 检查该用户是否已有档案
			const existRes = await db.collection('dh-patients')
				.where({
					user_id: data.user_id,
					hospital_id: patientData.hospital_id
				})
				.count();

			if (existRes.total > 0) {
				return formatResponse(400, null, '该患者档案已存在');
			}

			const res = await db.collection('dh-patients').add(patientData);
			return formatResponse(201, { _id: res.id }, '患者档案创建成功');
		} catch (error) {
			return formatError(error, '创建患者档案失败');
		}
	},

	/**
	 * 更新患者档案
	 */
	async updatePatient(id, data) {
		try {
			if (!id) {
				return formatResponse(400, null, '患者ID不能为空');
			}

			const updateData = {
				...data,
				update_time: Date.now()
			};

			// 移除不应该更新的字段
			delete updateData._id;
			delete updateData.user_id;
			delete updateData.hospital_id;
			delete updateData.create_time;

			await db.collection('dh-patients').doc(id).update(updateData);
			return formatResponse(200, null, '患者档案更新成功');
		} catch (error) {
			return formatError(error, '更新患者档案失败');
		}
	},

	/**
	 * 删除患者档案
	 */
	async deletePatient(id, reason = '') {
		try {
			if (!id) {
				return formatResponse(400, null, '患者ID不能为空');
			}

			const uniIdToken = this.getUniIdToken();
			const result = await softDelete('dh-patients', id, uniIdToken?.uid || '', reason);
			
			if (result.code === 200) {
				return formatResponse(200, null, '患者档案已移至回收站');
			} else {
				return formatResponse(result.code, null, result.message);
			}
		} catch (error) {
			return formatError(error, '删除患者档案失败');
		}
	},

	/**
	 * 批量删除患者档案
	 */
	async batchDeletePatients(ids, reason = '') {
		try {
			if (!ids || !Array.isArray(ids) || ids.length === 0) {
				return formatResponse(400, null, '患者ID列表不能为空');
			}

			const uniIdToken = this.getUniIdToken();
			const result = await batchSoftDelete('dh-patients', ids, uniIdToken?.uid || '', reason);
			
			if (result.code === 200) {
				return formatResponse(200, null, `成功删除${ids.length}条患者档案，已移至回收站`);
			} else {
				return formatResponse(result.code, null, result.message);
			}
		} catch (error) {
			return formatError(error, '批量删除患者档案失败');
		}
	}
};

